﻿using System;
using System.Globalization;
using System.Web;
using System.Web.Security;
using OpenPhotoAlbum.BusinessLogics;
using OpenPhotoAlbum.Controls;

namespace OpenPhotoAlbum
{
    public partial class Join : AlbumPage
    {
		private const string VSK_CAPTCHA_DATA = "cd";

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

			this.Title = StringUtility.AddAppPrefix(Resources.Strings.Title_Join);

            ltrUserName.Text = StringUtility.AddColon(Resources.Strings.UserName);
            ltrPassword.Text = StringUtility.AddColon(Resources.Strings.Password);
            ltrConfirmPassword.Text = StringUtility.AddColon(Resources.Strings.Join_ConfirmPassword);
            ltrEmail.Text = StringUtility.AddColon(Resources.Strings.Email);
            ltrOptional.Text = StringUtility.AddBrackets(Resources.Strings.Optional);
			ltrCode.Text = StringUtility.AddColon(Resources.Strings.Join_Code);
            ltrBenefit.Text = Resources.Strings.Join_EmailBenefit;
			cbUserAgreement.Text = StringUtility.Format(
				Resources.Strings.Join_UserAgreement,
				StringUtility.Format(
					"<a href=\"{0}\" target=\"_blank\" tabindex=\"7\">{1}</a>",
					Links.UserAgreement,
					Resources.Strings.UserAgreement));
            btnJoin.Text = Resources.Strings.Submit;
        }

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			if (!IsPostBack)
			{
				int number = CaptchaDataServices.Instance.GenerateRandomNumber();
				string data = CaptchaDataServices.Instance.Encrypt(number);
				imgCode.ImageUrl = UrlContext.BuildPhotoPipeCaptchaUrl(HttpUtility.UrlEncode(data));
				ViewState[VSK_CAPTCHA_DATA] = data;
			}
		}

		protected override void AppendSiteMapNodes(AlbumSiteMapProvider provider)
		{
			base.AppendSiteMapNodes(provider);

			provider.AppendSiteMapNode(Resources.Strings.SC_Home, Links.Default);
			provider.AppendSiteMapNode(Resources.Strings.JoinNow, RawUrl);
		}

        protected void btnJoin_Click(object sender, EventArgs e)
        {
            string userName = tbUserName.Text.Trim();
            string password = tbPassword.Text.Trim();

			msgError.MessageType = MessageTypes.FailMessage;

            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                msgError.Text = Resources.Strings.Login_IncompleteInput;
                return;
            }

			string captchaData = (string)ViewState[VSK_CAPTCHA_DATA];
			int number = CaptchaDataServices.Instance.Decrypt(captchaData);
			int userInputNumber;
			try
			{
				userInputNumber = int.Parse(tbCode.Text);
				if (userInputNumber != number) { throw new FormatException(); }
			}
			catch (FormatException)
			{
				msgError.Text = Resources.Strings.WrongVerificationCode;
				return;
			}

			if (tbPassword.Text != tbConfirmPassword.Text)
			{
				msgError.Text = Resources.Strings.Join_InconsistentPasswords;
				return;
			}

			if (!cbUserAgreement.Checked)
			{
				msgError.Text = Resources.Strings.Join_UserAgreementErrMsg;
				return;
			}
			
            
            string email = tbEmail.Text.Trim();

            if (UserManager.Instance.IsUserNameUsed(userName))
            {
                msgError.Text = Resources.Strings.Join_UserNameNotAvailable;
                return;
            }

			if (!UserManager.Instance.IsUserNameLegal(userName))
			{
				msgError.Text = Resources.Strings.Join_UserNameNotAvailable;
				return;
			}

			#region Check String Length

			if (UserManager.Instance.IsUserNameTooLong(userName))
			{
				msgError.Text = Resources.Strings.Join_UserNameTooLong;
				return;
			}

			if (UserManager.Instance.IsPasswordTooLong(password))
			{
				msgError.Text = Resources.Strings.Join_PasswordTooLong;
				return;
			}

			if (UserManager.Instance.IsEmailTooLong(email))
			{
				msgError.Text = Resources.Strings.Join_EmailTooLong;
				return;
			}

			#endregion

			// create
			Guid userId = UserManager.Instance.CreateNewUser(userName, password, email);

            if (!ValidateCreationResult(userId, userName, password)) { return; }

            CreateSampleAlbum(userId);

            FormsAuthentication.SetAuthCookie(userName, false);
            Response.Redirect(Links.MyHome);
        }

        private bool ValidateCreationResult(Guid userId, string userName, string password)
        {
            if (userId == null || userId.Equals(Guid.Empty))
            {
                msgError.Text = Resources.Strings.Join_UserNameNotAvailable;
                return false;
            }

            if (!UserManager.Instance.ValidateUser(userName, password))
            {
                msgError.Text = Resources.Strings.Join_FailedToCreateNewUser;
                return false;
            }

            DbAccess.User user = UserManager.Instance.GetUser(userName);

            if (user == null || !user.UserId.Equals(userId))
            {
                msgError.Text = Resources.Strings.Join_FailedToCreateNewUser;
                return false;
            }

            return true;
        }

        private void CreateSampleAlbum(Guid userId)
        {
			string title = Resources.Strings.My_MyFirstAlbumTitle;
			string description = StringUtility.Format(
				Resources.Strings.My_MyFirstAlbumDescription,
				Resources.Strings.My_CreateNewAlbum);

            Guid albumId = AlbumManager.Instance.CreateNewAlbum(userId, title, description);

            if (albumId == null || albumId.Equals(Guid.Empty)) { throw new FailedToCreateAlbumException(); }
        }
    }
}
